/*
Author: Surpass-HC
Source: https://gitee.com/hxchuan000/clpc-1
Mail: surpass-hc@qq.com
*/
#include <cstrCmd.h>
#include <logbase.h>

static int cStrCmdSortCmp(const void *cmp1, const void *cmp2)
{
    
    const cStrCmdInfStc *cmd1 = (const cStrCmdInfStc *)cmp1;
    const cStrCmdInfStc *cmd2 = (const cStrCmdInfStc *)cmp2;
    return strcmp(cmd1->cmdName, cmd2->cmdName);
}

int cStrCmdMgrInit(cStrCmdMgrStc *scmPtr, cStrCmdInfStc *cfgCmdList, int cfgNbr, void *cfgUsr)
{
    if(!(scmPtr && cfgCmdList && (cfgNbr > 0)))
    {
        printf("error cmd mgr init err:\n");
        return -1;
    }
    scmPtr->usrData = cfgUsr;
    scmPtr->cmdBuf = cfgCmdList;
    scmPtr->cmdNbr = cfgNbr;
    qsort(scmPtr->cmdBuf, scmPtr->cmdNbr, sizeof(scmPtr->cmdBuf[0]), cStrCmdSortCmp);
    return scmPtr->cmdNbr;
}
int cStrCmdMgrDoCmd(cStrCmdMgrStc *scmPtr, const char *doName, void *cmdData)
{
    cStrCmdInfStc tmpDoCmd;
    cStrCmdInfStc *tmpFndCmd;
    if(!(scmPtr && doName))
    {
        logdebugc("error cmd mgr do err:\n");
        return -1;
    }
    tmpDoCmd.cmdName = doName;
    tmpFndCmd = (cStrCmdInfStc *)bsearch(&tmpDoCmd, scmPtr->cmdBuf, scmPtr->cmdNbr, sizeof(scmPtr->cmdBuf[0]), cStrCmdSortCmp);
    if(!tmpFndCmd)
    {
        logdebugc("error cmd mgr not find:%s\n", doName);
        return -1;
    }
    if(!tmpFndCmd->cmdFun)
    {
        logdebugc("error cmd mgr func null:%s\n", doName);
        return -1;
    }
    return tmpFndCmd->cmdFun(cmdData, scmPtr->usrData);
}

int cStrCmdMgrPrtCmd(cStrCmdMgrStc *scmPtr)
{
    int i = 0;
    if(!(scmPtr))
    {
        logdebugc("error cmd mgr print err:\n");
        return -1;
    }
    logdebugc("cStrCmd print infor: size = %d", scmPtr->cmdNbr);
    for(i = 0; i < scmPtr->cmdNbr; i++)
    {
        logdebugc("cmd:%-20s, exp:%s", scmPtr->cmdBuf[i].cmdName, scmPtr->cmdBuf[i].cmdExplain);
    }
    return 1;
}

